package package1;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.atomic.AtomicLong;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import net.sf.json.JSONObject;


class Person {
	String name;

	public Person(String name) {
		this.name = name;
	}
}

/**
 * poll method paraChangedByMethod (if transfer the object, it would be changed)
 * 
 * @author Alvin.Wang
 *
 */
public class TestForCoreJava {
	public static String DESKTOP = "c:\\users\\alvin.wang\\desktop";

	public static void main(String[] args) throws Exception {
		int i = 0;
		Boolean goon = true;
		while(goon){
			System.err.println(i++);
			if(i==5)
				goon = null;
		}
		System.err.println("over");
		
		//		mapTest();
//		subListTest();
//		removeLineNumber();
		// open(System.getProperty("user.dir"));
		// user.dir D:\Program Files\workspace\JavaLearning
		// user.home : C:\Users\alvin.wang
		// user.name Alvin.Wang

		// mapCompareTest();
		// pollMethodForLinkedList();
		// paraChangedByMethod();
		// javaOpenLocalExe();
		// digitShift();
		// howToGetClassFileAddress();
		// testForFolderAndFileCopy();
		// log("1","2","3");
	}
	
	private static String open(File f) throws IOException {
		java.awt.Desktop.getDesktop().open(f);
		return f.getAbsolutePath();
	}

	public static void print(Cell c) {
		if(c!=null)System.err.println("("+c.getColumnIndex()+","+c.getRowIndex()+")"+c.getStringCellValue());
	}
	public static Workbook getWorkbook(File file) throws IOException {
		InputStream is = new FileInputStream(file);
		Workbook wb = null;
		if (file.getName().endsWith(".xlsx"))// 2007 .xlsx
			wb = new XSSFWorkbook(is);
		else if (file.getName().endsWith(".xls"))// 2003 .xls
			wb = new HSSFWorkbook(is);
		else
			throw new IOException("invalid file for excel");
		return wb;
	}

	private static void print(Map<?extends Object, ?extends Object> map) {
		for(Object k:map.keySet())System.err.println(k.toString()+":"+map.get(k));
	}



	private static void testForRoadShow() throws IOException {
		ArrayList<String>list = new ArrayList<String>();
		String file = "C:\\Users\\User\\Desktop\\111.txt";
		File f = new File(file);
		BufferedReader br = new BufferedReader(new FileReader(f));
		String buf;
		while((buf=br.readLine())!=null){
			if(buf.equals(""))continue;
			list.add(buf);
		}
		br.close();
		String logFile = getDesktop()+"\\faillog.txt";
		clearFileContent(logFile);
		System.err.println(list);
		for(String rsId:list){
			String url = "http://sse.roadshow.com/sseroadshow/m_public/getRsDetailInfo.do?rsId="+rsId;
			downloadTest(url);
		}
		open(getDesktop()+"\\faillog.txt");
	}



	private static void clearFileContent(String logFile) throws IOException {
		clearFileContent(new File(logFile));
	}



	private static void clearFileContent(File file) throws IOException {
		BufferedWriter bw = new BufferedWriter(new FileWriter(file,false));
		bw.write("");
		bw.close();
	}



	private static void downloadTest(String u) throws IOException {
		int rsId=0;
		rsId = Integer.parseInt(u.substring(u.lastIndexOf("=")+1));
		URL url = new URL(u);
//		InetSocketAddress isa = new InetSocketAddress("web-proxy.corp.hp.com", 8080);
//		Proxy proxy = new Proxy(Proxy.Type.HTTP, isa);
		// System.getProperties().put("proxySet", "true");
		// System.getProperties().put("proxyHost", "web-proxy.corp.hp.com");
		// System.getProperties().put("proxyPort", "8080");
		URLConnection con = null;
		InputStream is = null;
		boolean error = false;
		try {
			con = url.openConnection();
			is = con.getInputStream();
		} catch (Exception e) {
			error = true;
//			System.err.println("111");
//			System.err.println(e.getMessage());
//			System.err.println("111");
//			for(StackTraceElement a :e.getStackTrace()){
//				System.err.println("11111");
//				System.err.println(a.toString());
//				System.err.println("11111");
//			}
//			System.err.println("错误:"+e.getStackTrace());
		}finally{
			System.err.println("最后！！！");
			if(error){
				String f = getDesktop()+"\\faillog.txt";
				logToFile(f,rsId+"");
				return;
			}
		}
		
		InputStreamReader isr = new InputStreamReader(is, "utf-8");
		BufferedReader br = new BufferedReader(isr);
		String temp;
		StringBuffer sb = new StringBuffer();
		System.err.println("begin to write!");
		while ((temp = br.readLine()) != null)
			sb.append("\n" + temp);
		String folderAddr = "C:\\Users\\User\\Desktop\\test\\";
		File f = new File(folderAddr+"rs"+rsId+".html");
		
		FileOutputStream fos = new FileOutputStream(f);
		OutputStreamWriter osw = new OutputStreamWriter(fos, "utf-8");
		BufferedWriter bw = new BufferedWriter(osw);
		bw.write(sb.toString());
		br.close();
		bw.flush();
		bw.close();
		
//		System.err.println(sb);
		System.err.println("***success***");
		
	}



	private static void logToFile(String file, String str) throws IOException {
		BufferedWriter bw = new BufferedWriter(new FileWriter(new File(file),true));
		bw.write(str+"\r\n");
		bw.close();
	}



	private static Date getDate(String o1) {
		Date d = new Date();
		int year = d.getYear();
		int month = Integer.valueOf(o1.split("月")[0])-1;
		int date = Integer.valueOf(o1.split("日")[0].split("月")[1]);
		int min = Integer.valueOf(o1.split(" ")[1].split(":")[0]);
		int sec = Integer.valueOf(o1.split(" ")[1].split(":")[1]);
		return new Date(year,month,date,min,sec);
	}



	private static void getParameterName(String a) {
		
	}



	private static List<Map> jsonParseTest(String str, String nodeName) throws IOException {
		File f = new File(getDesktop()+"/1.jsp");
		BufferedReader br = new BufferedReader(new FileReader(f));
		nodeName = "live_videos";
		str = br.readLine();
		
		net.sf.json.JSONObject jsonObj = new net.sf.json.JSONObject();
		jsonObj = net.sf.json.JSONObject.fromObject(str);
		List<Map> mapList = (List<Map>) jsonObj.get(nodeName);
		Object title = mapList.get(0).get("title");
		return mapList;
	}



	private static void mapTest() {
		Map m = new HashMap();
		m.put("a", null);
		m.put("b", null);
		System.err.println(m);
		
		
	}



	private static void subListTest() {
		ArrayList<String> l = new ArrayList<String>();
		l.add("a");
		l.add("b");
		l.add("c");
		List<String> a = l.subList(0, 2);
		System.err.println(a);
	}



	private static void removeLineNumber() throws IOException {
		File f1 = new File(getDesktop() + "\\1.jsp");
		BufferedReader br = new BufferedReader(new FileReader(f1));
		String buf;
		while ((buf = br.readLine()) != null) {
			boolean condition = buf.contains(".");
			condition = !buf.startsWith("package");
			if (condition) {
				int a = buf.indexOf(".");
				System.err.println(buf.substring(a + 1, buf.length()));
			} else
				System.err.println(buf);
		}
		br.close();
	}

	@SuppressWarnings("unused")
	private static String getCurrentEnv() {
		String dir = System.getProperty("user.dir");
		String env = "WORKSPACE";
		if (dir.toLowerCase().contains("desktop"))
			env = "DESKTOP";
		return env;
	}

	private static String getDesktop() {
		return System.getenv("USERPROFILE") + "\\desktop\\";
	}

	@SuppressWarnings("unused")
	private static void methodTest(ArrayList<Integer> a) {
		a.set(0, 20);
	}

	@SuppressWarnings("unused")
	private static void methodTest(int a, int b) {
		a = 3;
		b = 4;
	}

	@SuppressWarnings("unused")
	private static void mapCompareTest() {
		HashMap<String, String> m1 = new HashMap<String, String>();
		HashMap<String, String> m2 = newMap();
		m1.put("a", "1");
		m1.put("b", "2");
		m1.put("c", "3");
		m2.put("a", "a");
		m2.put("b", "b");
		m2.put("d", "d");
		System.err.println("\tm1\tm2");
		for (String a : m1.keySet()) {
			if (m2.containsKey(a)) {
				System.err.println(a + "\t" + m1.get(a) + "\t" + m2.get(a));
			} else
				System.err.println(a + "\t" + m1.get(a) + "\t");
		}

		Set<String> s1 = m1.keySet();
		Set<String> s2 = m2.keySet();
		s2.removeAll(s1);
		for (String a : s2) {
			System.err.println(a + "\t" + "" + "\t" + m2.get(a));
		}
	}

	private static HashMap<String, String> newMap() {
		return new HashMap<String, String>();
	}

	@SuppressWarnings("unused")
	private static void readFileToMap(String f1, Map<String, String> m1) throws IOException {
		BufferedReader br1 = new BufferedReader(new FileReader(f1));
		String b1;
		while ((b1 = br1.readLine()) != null) {
			m1.put(b1.split("#")[0].trim(), b1.split("#")[1].trim());
		}
		br1.close();
	}

	@SuppressWarnings("unused")
	private static void log(String... arr) throws IOException {
		BufferedWriter bw = new BufferedWriter(new FileWriter("log.txt"));
		for (String a : arr)
			bw.write(a + "\r\n");
		bw.close();
	}

	public static void openCurrentFolder() throws IOException {
		open(getCurrentFolder());
	}

	private static String getCurrentFolder() {
		return System.getProperty("user.dir");
	}

	@SuppressWarnings("unused")
	private static void testForFolderAndFileCopy() throws Exception {
		String f1 = "c:/users/alvin.wang/desktop/1";
		String f2 = "c:/users/alvin.wang/desktop/two";
		copyToFolder(new File(f1).listFiles(), f2);
		open(f2);
	}

	private static void copyToFolder(File[] files, String folder) throws Exception {
		folderCheck(new File(folder));
		copyToFolder(files, new File(folder));// files to folder
	}

	private static void copyToFolder(File[] files, File folder) throws Exception {
		folderCheck(folder);
		for (File f : files) {
			if (f.isDirectory())
				copyToFolder(f, folder);// folder to folder
			else
				copyToFile(f, folder + "\\" + f.getName());// file to folder
		}
	}

	private static void copyToFolder(File folder1, File folder2) throws Exception {
		folderCheck(folder2);
		// create f1 folder in f2
		File f = new File(folder2, folder1.getName());
		if (!f.exists())
			f.mkdirs();
		// copy f1 contents File[] to f2
		copyToFolder(folder1.listFiles(), folder2);// files to folder
	}

	private static void folderCheck(File file) throws Exception {
		if (!file.isDirectory())
			throw new Exception(file.getName() + " is not a directory");
	}

	private static void copyToFile(File f1, String f2Addr) throws Exception {
		File f2 = new File(f2Addr);
		if (f2.isDirectory())
			copyToFolder(f1, f2);
		else
			copyToFile(f1, f2);
	}

	@SuppressWarnings("unused")
	private static void copyToFile(String f1, String f2) throws Exception {
		copyToFile(new File(f1), new File(f2));
	}

	private static void copyToFile(File f1, File f2) throws Exception {
		boolean deleted = true;
		if (f2.exists()) {
			deleted = f2.delete();
			if (!deleted)
				throw new Exception("File " + f2.getName() + " is in use, thus cannot be deleted!");
		}
		boolean needDealingWithLine = false;
		if (needDealingWithLine) {
			BufferedReader br = new BufferedReader(new FileReader(f1));
			BufferedWriter bw = new BufferedWriter(new FileWriter(f2));
			String buf;
			while ((buf = br.readLine()) != null)
				bw.write(buf + "\r\n");
			br.close();
			bw.close();
		} else {
			BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f1));
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f2));
			byte[] b = new byte[1024];
			int pos;
			while ((pos = bis.read(b)) != -1) {
				bos.write(b, 0, pos);
				bos.flush();
			}
			bis.close();
			bos.close();
		}
	}

	private static void open(String f1) throws IOException {
		java.awt.Desktop.getDesktop().open(new File(f1));
	}

	private static void run(String s) throws IOException {
		Runtime.getRuntime().exec(s);
	}

	@SuppressWarnings("unused")
	private static void run(File b) throws IOException {
		String cmd = "java " + b.getName().replace(".class", "");
		System.err.println("cmd:" + cmd);
		run(cmd);
	}

	@SuppressWarnings("unused")
	private static void howToGetClassFileAddress() throws IOException {
		String a = new TestForCoreJava().getClass().getProtectionDomain().getCodeSource().getLocation().toString();
		String c = URLDecoder.decode(a, "utf-8");
		System.err.println(c);
		// file:/D:/Program Files/Java/WorkSpace/JavaLearning/bin/

		String a1 = Thread.currentThread().getContextClassLoader().getResource("").toString();
		String c1 = URLDecoder.decode(a1, "utf-8");
		System.err.println(c1);
		// file:/D:/Program Files/Java/WorkSpace/JavaLearning/bin/

		String a2 = System.getProperty("user.dir");
		System.err.println(a2);
		// D:\Program Files\Java\WorkSpace\JavaLearning

		String b = Thread.currentThread().getStackTrace()[1].getClassName();
		System.err.println(b);
		String c3 = b.replace(".", "\\");
		System.err.println(c3);

		Map<String, String> map = System.getenv();
		for (String c4 : map.keySet())
			System.err.println(c + "=" + map.get(c4));
		System.exit(0);
	}

	@SuppressWarnings("unused")
	private static void digitShift() {
		int a = 6;
		int b = 8;
		int c = (a + b) >> 1;
		System.err.println(c);
	}

	@SuppressWarnings("unused")
	private static void paraChangedByMethod() {

		// if the content would be changed depends on whether the converted
		// parameter is a value or an object
		// it changes if the object is converted

		int[] a1 = { 1, 1 };
		deal(a1);
		System.err.println(a1[0]);
		// array would be changed

		boolean b1 = false;
		deal(b1);
		System.err.println(b1);
		// boolean would not be affected

		Person p = new Person("a");
		deal(p);
		System.err.println(p.name);
		// a class property would also be affected
	}	

	private static void deal(Person p) {
		p.name = "b";
	}

	private static void deal(boolean b1) {
		b1 = true;
	}

	private static void deal(int[] a1) {
		a1[0] = 0;
	}

	@SuppressWarnings("unused")
	private static void pollMethodForLinkedList() {
		LinkedList<String> list = new LinkedList<String>();
		list.add("1");
		list.add("2");
		list.add("3");
		list.add("4");
		System.err.println("LinkedList:" + list);
		System.err.println("Head element of the list:" + list.poll());
		System.err.println("LinkedList:" + list);
		System.err.println("Head element of the list2:" + list.poll());
		System.err.println("LinkedList:" + list);
		System.err.println("Head element of the list3:" + list.poll());
		System.err.println("LinkedList:" + list);
		System.err.println("Head element of the list4:" + list.poll());
		System.err.println("LinkedList:" + list);
	}
}
